#include "Environment2D.h"
#include <iostream>
#include "tinyxml.h"

Environment2D::Environment2D(void)
{
}


Environment2D::~Environment2D(void)
{
}

bool Environment2D::loadXml(const std::string& xmlName)
{
	obstacles_.clear();

	std::cout << "Loading from xml: " << xmlName << "\n";
	TiXmlDocument xml( xmlName );
	bool loadOkay = xml.LoadFile();

	// Make sure that the xml was well-formed
	if ( !loadOkay ) {	// load xml file
		std::cerr << "Could not load simulation xml " << xmlName << ".\n";
		return false;
	}

	TiXmlElement* experimentNode = xml.RootElement();	
	if( ! experimentNode ) {
		std::cerr << "Root element does not exist.\n";
		return false;
	}

	// Make sure the root tag is what you expect
	if( experimentNode->ValueStr () != "Experiment" ) {
		std::cerr << "Root element value is not 'Experiment'.\n";
		return false;
	}

	// Now parse the child tags of the expermient node
	TiXmlElement* child;
	for( child = experimentNode->FirstChildElement(); child; child = child->NextSiblingElement()) {
		if ( child->ValueStr() == "Obstacle" ) {
			obstacles_.push_back(Obstacle());
			obstacles_.back().parseXml( child );
		} else {
			// You can ignore unexpected tags or report a problem.  In this case, we'll report a problem
			std::cerr << "Encountered an unexpected tag: " << child->ValueStr() << "\n";
			return false;
		}
	}
	return true;
}

void Environment2D::render()
{
	for (unsigned int i = 0; i < obstacles_.size(); ++i)
		obstacles_[i].render();
}

void Environment2D::getBoundingBox(int& left, int& right, int& top, int& bottom) const
{
	for (unsigned int i = 0; i < obstacles_.size(); ++i)
	{
		if (obstacles_[i].isBoundingBox())
		{
			obstacles_[i].getBoundingBox(left, right, top, bottom);
		}
	}
}

bool Environment2D::clear(const Vector2& v, float radius) const
{
	for (unsigned int i = 0; i < obstacles_.size(); ++i)
	{
		if (obstacles_[i].clear(v, radius) == false)
			return false;
	}
	return true;
}

bool Environment2D::link(const Vector2& from, const Vector2& to, float radius) const
{
	for (unsigned int i = 0; i < obstacles_.size(); ++i)
	{
		if (obstacles_[i].link(from, to, radius) == false)
			return false;
	}
	return true;
}